# _*_ encoding: utf-8 _*_
import optparse

class FileGroupWriter:
    def __init__(self, f_prefix, f_number):
        self.prefix = f_prefix
        self.n = f_number
        self.f_handles = []
    def __enter__(self):
        for i in range(self.n):
            self.f_handles.append(open("{0}_{1}".format(self.prefix, i), "wb"))
        return self.f_handles

    def __exit__(self, exc_type, exc_val, exc_tb):
        if type:
            print(exc_val)
        for h in self.f_handles:
            h.close()
        return False

def get_options(args=None):
    optparser = optparse.OptionParser()

    optparser.add_option("-i", "--input", dest="fname", help="input file")
    optparser.add_option("-o", "--output-prefix", dest="prefix", help="output file prefix")
    optparser.add_option("-n", "--number", dest="n", type="int", help="number of output file")

    (options, args) = optparser.parse_args(args=args)

    if not options.fname or not options.prefix or not options.n:
        optparser.print_help()
        exit(0)

    return options

def process(line):
    elems = line.strip("\n").split(",")
    useful = [elems[0], elems[1], elems[4], elems[6], elems[7], elems[8]]
    return useful

def split(fname, prefix, n, header=False):
    with open(fname, "rb") as fin:
        with FileGroupWriter(f_prefix=prefix, f_number=n) as fout:
            if header:
                for f in fout:
                    f.write("id,time,angle,speed,pos,lane\n")
            for line in fin:
                res = process(line)
                mod = hash(res[0]) % n
                fout[mod].write("{0}\n".format(",".join(res)))

def main(options=None):
    split(options.fname, options.prefix, options.n)

if __name__ == '__main__':
    main(get_options())